const {
    formatDate
} = require("../../../utils/utilDay");
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';
const {apiBaseUrl} = require('../../../utils/config.js')

Page({
    data: {
        //总的
        totalCount: [],
        //分页
        showlist :[],
        page:1, 
        pagesize : 8, 
        //是否显示遮罩层
        show: true,
        percentage: `请选择吃了多少∨`,
        day: '请选择保质期',
        saveDay: ['1天', '2天', '3天', '4天', '5天', '6天', '7天', '8天', '9天', '10天', '11天', '12天', '13天', '14天'],
        eatArray: ['10%', '20%', '30%', '40%', '50%', '60%', '70%', '80%', '90%', '100%'],
        eatBaifen :[],
        showPlus: true,
        Default:'请选择吃多少',
        expire: [],
        tupianUrl: "",
        expireForm:""//存储遮罩层表单的保质期
    },
    //触底事件 
    onReachBottom () {
        wx.showLoading({
          title: '加载中',
        })
        let shu = this.data.page
        this.setData({
          page:shu+1
        })
        let num = (this.data.page-1)*this.data.pagesize   
        let num2 = num+this.data.pagesize
        let arr = this.data.totalCount
        let qielist = arr.slice(num,num2)
        for (var i = 0; i < qielist.length; i++) {
            qielist[i].creatDate = qielist[i].creatDate.split("T")[0];
            qielist[i].expirationDate = qielist[i].expirationDate.split("T")[0];
            var date1 = new Date(qielist[i].creatDate).getTime();
            var date2 = new Date(qielist[i].expirationDate).getTime();
            var surplus = date2 - date1;
            if(surplus<0){
              this.setData({
                  expire: this.data.expire.concat("过期")
              });
            }
            else 
            this.setData({
                expire: this.data.expire.concat(parseInt(surplus / (1000 * 60 * 60 * 24)))
            });
        }
        let slist = this.data.showlist
        let newarr = slist.concat(qielist)
        this.setData({
          showlist:newarr
        })
        // console.log(this.data.showlist);
        setTimeout(function () {
          wx.hideLoading()
        }, 300)
      },
    //点击添加显示遮罩层
    clearForm() {
        this.setData({
            caiMing: '',
            caiCount: '',
            expireForm: '',
            imagePath: '',
            showPlus: true,
        })
    },
    HuiSu () { 
        this.setData({
            show : true
        })
    },
    loginFormData(e) {
        console.log(e);
    },
    handleChooseAlbum() {
        //系统API，让用户在相册中选择图片（或者拍照）
        wx.chooseImage({
            success: (res) => {
                //1、取出路径
                const path = res.tempFilePaths[0]
                //2、设置imagePath
                this.setData({
                    imagePath: path,
                    showPlus: false
                })
            }
        })
    },
    uploadTuChuang() {
        // console.log(this.data.imagePath);
        wx.uploadFile({
            url: 'https://sm.ms/api/v2/upload',
            method: 'POST',
            header: {
                'Content-Type': 'multipart/form-data',
                'Authorization': 'fqEiVEl584JZVxVJEkx2weiQ7IVswWEN',
            },
            data: {
                'format': 'json'
            },
            filePath: this.data.imagePath,
            name: 'smfile',
            success: (res => { console.log(res);
                if (res.statusCode == 200) {
                    var data = JSON.parse(res.data)
                    if (data.success) {
                        console.log(data.data.url)
                        this.setData({
                            tupianUrl: data.data.url
                        })
                    }
                }
            })
        })
    },
    // handle caiming 
    hanldeCaiMing(e) {
        let input_caiming = e.detail.value;
        // console.log(input_caiming);
        this.setData({
            caiMing: input_caiming
        })
    },
    // handleBaoZhi 
    handleBaoZhi(e) {
        let handle_BaoZhi = e.detail.value;
        // console.log(handle_BaoZhi);
        this.setData({
            expireForm: handle_BaoZhi
        })
    },
    // count 
    handleCaiCount(e) {
        let handle_CaiCount = e.detail.value;
        // console.log(handle_CaiCount);
        this.setData({
            caiCount: handle_CaiCount
        })
    },
    submit() {
        // 获取当前日期时间
        const now = new Date();
        // 格式化日期时间
        // const formatted = now.toLocaleString('en-US', { timeZoneName: 'short' });
        console.log(now);
        this.uploadTuChuang();
        wx.showLoading({
          title: '添加数据中',
        })
        setTimeout(() => {
            let url = `${apiBaseUrl}goods/add/` + '231/' + this.data.caiMing + '/' + this.data.caiCount + '/' + '很好吃' + '/' + `${now}/` + '根/' + '冷藏' + "?photoUrl=" + this.data.tupianUrl;
             console.log(url);
            wx.request({
                url: url,
                method: 'GET',
                header: {
                    'content-type': 'application/json' // 默认值
                },
                success: (res => {
                    console.log(res);
                    if(res.data.code == 200 ) {
                        Toast.success('添加成功');
                        this.onLoad();
                    }else {
                        Toast.fail('添加失败');
                    }
                    wx.hideLoading();
                    this.clearForm();
                    this.HuiSu();
                })
            })
        }, 6000)
    },
    clickBtn(e) {
        // console.log(this.data.caiMing);
        this.setData({
            show: !this.data.show,
            caiMing: '',
            caiCount: '',
            expireForm: '',
            imagePath: '',
        })
    },
    //食用量百分比
    bindPickerChange(e) {
        let diji = e.detail.value;
        let index=e.currentTarget.dataset.id;
        let eatBai = (++diji) +"0%"
        this.setData({
            ["eatBaifen["+index+"]"]:eatBai
        })
    },
    deadline(e) {
        this.setData({
            day: this.data.saveDay[parseInt(e.detail.value)]
        })
    },
    onReady() {
      wx.showLoading({
          title: '加载中...',
      })
      let userInfo = wx.getStorageSync('userInfo')
      setTimeout(function () {
          wx.hideLoading();
      }, 500),
      // 冰箱首页数据
      wx.request({
        url: `${apiBaseUrl}goods/list/${userInfo.userBid}/1/100`,
        success: (res) => {
            console.log(res);
            let total = res.data.data.records;
            let list = total;
            let _this = this;
            // 正确计算截取的起始和结束索引
            let startIndex = (_this.data.page - 1) * _this.data.pagesize;
            let endIndex = startIndex + _this.data.pagesize;
            let qielist = list.slice(startIndex, endIndex);
    
            for (var i = 0; i < qielist.length; i++) {
                let x = total[startIndex + i].expirationDate.split('T')[0];
                qielist[i].creatDate = x;
                let y = total[startIndex + i].creatDate.split('T')[0];
                qielist[i].expirationDate = y;
                var date1 = new Date(x).getTime();
                var date2 = new Date(y).getTime();
                var surplus = date1 - date2;
                this.setData({
                    expire: this.data.expire.concat(parseInt(surplus / (1000 * 60 * 60 * 24)))
                });
            }
            this.setData({
                totalCount: total,
                expire: this.data.expire.map(res => res + '天'),
                showlist: qielist
            });
        }
    });
  }
})